package smodul

import (
	"WeChatMGRA/server/conf"
	"fmt"
	"gitee.com/yutiandou/wdtools/wdevent"
	"gitee.com/yutiandou/wdtools/wdlog"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var MysqlDB * gorm.DB

//ConnectDB ..加载数据库并在程序结束时关闭数据库
func ConnectDB(conf * conf.Config)error{
	var err error
	MysqlDB,err = gorm.Open("mysql",fmt.Sprintf( "%s:%s@(%s:%s)/wechatmgra?charset=utf8&parseTime=true",conf.MysqlUser,conf.MysqlPasswd,conf.MysqlAddress,conf.MysqlPort))
	if err!=nil{
		return err
	}
	wdevent.AddEvent("DataStoreToMysql",func(data interface{}){
		MysqlDB.Close()
		wdlog.Warning("数据库关闭")
		wdevent.ExecEvent("MysqlCloseSuccess",nil)
	})
	MysqlDB.SingularTable(true)
	MysqlDB.DB().SetMaxOpenConns(1024)
	MysqlDB.DB().SetMaxIdleConns(32)
	wdlog.Warning("数据库连接成功...")
	//count:=0
	//if MysqlDB.Raw("SELECT count(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA='wechatmgra'").Scan(&count);count<=0{
	//	return errors.New("数据库为空，或连接异常")
	//}
	return nil
}